<template>
  <div
    class="breadCrumbMenuPage d-flex a-center"
    :class="
      router.currentRoute.value.path == '/asset/home'
        ? 'home-padding m-b20'
        : ''
    "
  >
    <div
      class="left-wrap d-flex a-center j-center m-t5"
      @click="onLeftArrow"
      :style="{
        '--left-arrow-background': isLeftDisable() ? '#ff7b50' : '#808080',
        '--left-arrow-cursor': isLeftDisable() ? 'pointer' : 'not-allowed',
      }"
    >
      <el-icon class="arrow_icon"><ArrowLeftBold /></el-icon>
    </div>
    <div class="menuTag-wrap">
      <div
        class="menuTag-content d-flex a-center"
        :style="{
          transform: `translateX(${translateX}px)`,
          width: menuTag_content_width + 'px',
        }"
      >
        <div
          class="menuTag2 d-flex a-center"
          v-for="(n, i) in store.state.menu.breadcrumbItemsArr"
          :key="i"
        >
          <div
            class="cursor"
            :class="router.currentRoute.value.path == n.path ? 'tagActive' : ''"
            @click="goPath(n.path,$event)"
          >
            {{n.title || n.name }}
          </div>
          <img
            class="btnBox"
            v-if="state.canCloseFlag"
            style="width: 19px; height: 19px"
            src="@/assets/iconImg/close.png"
            alt=""
            @click="doClose(n)"
          />
        </div>
      </div>
    </div>
    <div class="right-wrap d-flex a-center m-t5">
      <div
        @click.stop="onRightArrow"
        class="arrowRightBold-wrap d-flex a-center j-center"
        :style="{
          '--right-arrow-background': isRightDisable() ? '#ff7b50' : '#808080',
          '--right-arrow-cursor': isRightDisable() ? 'pointer' : 'not-allowed',
        }"
      >
        <el-icon class="arrow_icon"><ArrowRightBold /></el-icon>
      </div>
      <el-divider direction="vertical" />
      <div
        class="closeBold-wrap d-flex a-center j-center"
        @click="closeMenuTag"
        :style="{
          '--close-icon-cursor':
            store.state.menu.breadcrumbItemsArr.length > 1
              ? 'pointer'
              : 'not-allowed',
        }"
      >
        <el-icon class="arrow_icon"><CloseBold /></el-icon>
      </div>
      <svg-icon
        icon-class="refresh-icon"
        class="refresh-icon m-l10"
        @click="refresh"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, watch, ref, nextTick, computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  ArrowLeftBold,
  ArrowRightBold,
  CloseBold,
} from "@element-plus/icons-vue";
import { ElDivider, ElIcon } from "element-plus";
import {clearCache, getRootRouteItem} from "@/utils/createRoutes";

const router = useRouter();
const store = useStore();

let state = reactive({
  breadItemsArr: [],
  canCloseFlag: false,
  currentPath: "",
  currentIndex: 0,
});

const refresh = () => {
  store.commit("set_isLoading", true); // 展示数据加载状态
  store.commit("set_isRouterAlive", false); // 设置为false，卸载dom

  setTimeout(() => {
    // 此处采用了定时器，并没有采用网上比较常见的nextTick
    store.commit("set_isRouterAlive", true); // 设置为true，重新挂载dom
    store.commit("set_isLoading", false); // 隐藏数据加载状态
  }, 1000);
};

const menuTag_content_width = ref(0);
const countWidth = () => {
  let count = 0;
  let domArr = document.querySelectorAll(".menuTag2");
  domArr.forEach((dom) => {
    // count = count + dom.clientWidth + 25;
    count += dom.clientWidth;
  });
  return count;
};

/**
 * 初始化breadCrumbMenuPage组件的宽度
 *
 */
const _init = () => {
  translateX.value = 0;
  let menuWrap = document.querySelector(".menuTag-wrap");
  if (menuWrap) {
    // console.log("menuWrap", menuWrap.offsetWidth);
    menu_wrap_width.value = menuWrap.clientWidth;
    activeMenu();
    return;
  }
  menu_wrap_width.value = 100;
};

// 监听左边侧边栏的收缩
watch(
  () => store.state.menu.showMenuFlag,
  (newValue) => {
    setTimeout(() => {
      _init();
    }, 700);
  }
);

// 监听面包屑数据
watch(
  () => store.state.menu.breadcrumbItemsArr,
  (newValue) => {
    if (newValue.length > 1) {
      state.canCloseFlag = true;
    }
    // console.log('--menu.breadcrumbItemsArr--', newValue);
    menuTag_content_width.value = 0;
    nextTick(() => {
      menuTag_content_width.value = countWidth();
      activeMenu();
    });
  },
  { immediate: true, deep: true }
);

// 监听菜单路由变动
watch(() => router.currentRoute.value.path, (val) => {
  // console.log('---router.currentRoute.path---', val);
  nextTick(() => {
    activeMenu();
  });
});

// 菜单居中
let activeMenu = () => {
  let menuTab = document.querySelector('.tagActive');// 选中状态的菜单
  if (menuTab) {
    menuCenter(menuTab.parentElement);
  }
};
let menuCenter = (element) => {
  let moveNum = element.offsetLeft + (element.clientWidth - menu_wrap_width.value) / 2;
  let maxNum = menu_wrap_width.value - menuTag_content_width.value;
  // console.log('moveNum---', moveNum, 'maxNum---', maxNum);
  if (maxNum < 0) {
    if (moveNum > 0) {
      if (moveNum >= Math.abs(maxNum)) {
        translateX.value = maxNum;
      } else {
        translateX.value = -moveNum;
      }
    } else {
      translateX.value = 0;
    }
  } else {
    translateX.value = 0;
  }
}

const goPath = (path,event) => {
  router.push(path);
  // let el = event.target.parentElement;
  // menuCenter(el);
};


const doClose = (item) => {
  clearCache(item);
  let breadcrumbItemsArr = store.state.menu.breadcrumbItemsArr;
    console.log('breadcrumbItemsArr',breadcrumbItemsArr)
  if (breadcrumbItemsArr.length > 1) {
    breadcrumbItemsArr.map((n, i) => {
      if (getName(n) == getName(item)) {
        if (i == 0) {
          // 跳转到后一个
          router.push(breadcrumbItemsArr[i + 1].path);
        } else {
          // 跳转到前一个
          router.push(breadcrumbItemsArr[i - 1].path);
        }

        // 从指定位置删除一个
        store.commit("DELET_BREAD_ITEMS", i);

        // 只剩一个，隐藏关闭按钮
        if (breadcrumbItemsArr.length == 1) {
          state.canCloseFlag = false;
        }
      }
    });
  }
};

/**
 * 获取name
 */
const getName = (item) => {
  // console.log('item', item);
  if(item.name!==undefined && item.name!==''){
      return item.name;
  }
  if(item.title!==undefined && item.title!==''){
      return item.title;
  }
}

// 关闭所有菜单tag
const closeMenuTag = () => {
  clearCache();
  let breadcrumbItemsArr = store.state.menu.breadcrumbItemsArr;
  if (breadcrumbItemsArr.length > 1) {
    let route = getRootRouteItem(JSON.parse(JSON.stringify(store.state.menu.leftMenu)));
    store.commit("DELETE_BREAD_ITEMS_ALL",{path:route.path,title:route.meta.title});
    setTimeout(() => {
        // 获取根路由
      router.push({path: route.path});
      state.canCloseFlag = false;
    }, 600);
  }
};

const menu_wrap_width = ref(0);
const translateX = ref(0);

const onLeftArrow = () => {
  if (translateX.value < 0) {
    translateX.value = 0;
  }
};

const onRightArrow = () => {
  if (menu_wrap_width.value < menuTag_content_width.value) {
    translateX.value = menu_wrap_width.value - menuTag_content_width.value;
  }
};

const isLeftDisable = computed(() => () => {
  return translateX.value < 0;
});

const isRightDisable = computed(() => () => {
  let maxMove = menuTag_content_width.value - menu_wrap_width.value;
  return maxMove > 0 && Math.abs(translateX.value) < maxMove;
});

onMounted(() => {
  _init();
});
</script>

<style lang="scss" scoped>
.breadCrumbMenuPage {
  margin-bottom: 35px;
  position: relative;
  //background: #4d4d4d;
  width: 100%;
  .left-wrap {
    .arrow_icon {
      color: #ffffff;
    }
    width: 25px;
    height: 25px;
    cursor: var(--left-arrow-cursor);
    background: var(--left-arrow-background);
    border-radius: 50%;
    margin-right: 20px;
  }
  .menuTag-wrap {
    white-space: nowrap;
    overflow: hidden;
    flex: 1;
    .menuTag-content {
      white-space: nowrap;
      transition: all 0.8s;
      //.menuTag2:last-child{
      //  margin-right: 0px !important;
      //}
    }
  }
  .right-wrap {
    //position: absolute;
    //right: 10px;
    margin-left: 20px;
    .arrowRightBold-wrap {
      width: 25px;
      height: 25px;
      cursor: var(--right-arrow-cursor);
      background: var(--right-arrow-background);
      border-radius: 50%;
    }
    .closeBold-wrap {
      width: 25px;
      height: 25px;
      cursor: var(--close-icon-cursor);
      background: #ff7b50;
      border-radius: 50%;
    }
    .refresh-icon {
      width: 29px;
      height: 29px;
    }
    .arrow_icon {
      color: #ffffff;
    }
    .close_icon {
      width: 30px;
      height: 30px;
      cursor: pointer;
    }
  }
  .menuTag2:hover .btnBox {
    display: block;
  }
  .menuTag2 {
    margin-bottom: 5px;
    font-size: 22px;
    color: $title-big-color;
    font-weight: bold;
    position: relative;
    display: inline-block;
    padding-right: 25px;
    margin-top: 10px;
    .tagActive {
      color: $title-sm-color;
    }

    .btnBox {
      display: none;
      position: absolute;
      right: 5px;
      top: -8px;
      cursor: pointer;
    }
  }
}
.home-padding {
  //padding-left: 15px;
  padding: 0 48px;
}
</style>
